package myShoppingCart

import (
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/controllers/login"
	USER "OnlineRetailers/models/User"
	"OnlineRetailers/models/User/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type GetMyShoppingCart struct {
	beego.Controller
}

func (c *GetMyShoppingCart) GetMyShoppingCart() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/myShoppingCart/GetMyShoppingCart"
	res := resMes.GetShoppingCarts{}
	shoppingCarts := []*USER.ShoppingCart{}
	log := &error2.Log{}
	var err error
	mes := &error2.Mes{}
	o := orm.NewOrm()

	//fmt.Println(c.Ctx.Request.Header)

	err, openid := login.CheckOpenid(c.Ctx.Request.Header["Openid"])
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	sql := "select * from `shopping_cart` where user_id=?"
	num, err := o.Raw(sql, openid).QueryRows(&shoppingCarts)
	//_, err = o.QueryTable("Activity").All(&activitys)
	fmt.Println(shoppingCarts)
	if num == 0 {
		c.Data["json"] = errorDeal.ErrLightMess(mes, "401", "无购物车")
		return
	}
	ch := make(chan int)
	go func() {
		for _, shoppingCart := range shoppingCarts {
			err = o.Read(shoppingCart.Product)
			if err != nil {
				ch <- -1
			} else {
				ch <- 1
			}
		}
	}()

	for range shoppingCarts {

		if <-ch == -1 {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return

		}
	}
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	res.ShoppingCart = shoppingCarts
	res.Code = "200"
	c.Data["json"] = res

}
